﻿using CBApi;
using CBApi.Models.Responses;
using JobSearcherAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JobSearcherAPI.Search
{
    internal class CareerBuilderSearcher
    {
        public SearchResult Search(SearchArguments searchArgs)
        {
            SearchResult returnResult = new SearchResult();

            try
            {
                ICBApi svc = API.GetInstance("", 2000); //API key goes here

                ResponseJobSearch result = svc.JobSearch()
                    .WhereKeywords(searchArgs.Keywords)
                    .WhereLocation(searchArgs.Location)
                    .WhereNotKeywords(searchArgs.Omitted)
                    .WherePostedWithin(searchArgs.DaysOld)
                    .WhereCountryCode(CBApi.Models.Service.CountryCode.US)
                    .OrderBy(CBApi.Models.OrderByType.Date)
                    .Ascending()
                    .Search();

                foreach (JobSearchResult job in result.Results)
                {
                    var newJob = new Job()
                    {
                        Title = job.JobTitle,
                        Description = job.DescriptionTeaser,
                        Company = job.Company,
                        PostDate = DateTime.Parse(job.PostedDate).Date,
                        Location = job.Location,
                        PostURL = job.JobDetailsURL
                    };
                    returnResult.Add(newJob);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error getting jobs: {0}", e.Message);
                return returnResult;
            }

            return returnResult;
        }
    }
}
